const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'
const ctime = require('../../time/conversion.js')

router.post('/getStationChangeInfo', async (req, res) => {
    //验证token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select * from user where username = ?'
    db.base(sql, result.username, response => {
        console.log(response)
        //验证成功则判定是否存在选择条件workNumber
        if (response.length > 0 ) {
            //若为空则返回所有的数据
            if (req.body.workNumber === null) {
                let sql = 'select * from station_changeInfo'
                db.base(sql, null, response => {
                    //处理时间，整合返回数据
                    let data = []
                    for (let i = 0; i< response.length; i++) {
                        ctime.formatUTC (response[i].occur_time, result => {
                            response[i].occur_time = result
                        })
                        data[i] = {
                            'workNumber': response[i].work_number,
                            'name': response[i].name,
                            'changeType': response[i].change_type,
                            'occurTime': response[i].occur_time,
                            'reason': response[i].reason,
                            'originStation': response[i].origin_station,
                            'desStation': response[i].des_station
                        }
                    }
                    // console.log(data)
                    res.json({ data })

                })
            }
            //不为空则返回查询的工号的数据
            else {
                let sql = 'select * from station_changeInfo where work_number = ?'
                db.base(sql, req.body.workNumber, response => {
                    // console.log(response)
                    //处理时间，整合返回数据
                    let data = []
                    for (let i = 0; i< response.length; i++) {
                        ctime.formatUTC (response[i].occur_time, result => {
                            response[i].occur_time = result
                        })


                        data[i] = {
                            'workNumber': response[i].work_number,
                            'name': response[i].name,
                            'changeType': response[i].change_type,
                            'occurTime': response[i].occur_time,
                            'reason': response[i].reason,
                            'originStation': response[i].origin_station,
                            'desStation': response[i].des_station
                        }
                    }
                    // console.log(data)
                    res.json({ data })
                })
            }
        }
    })

})

module.exports = router
